//
//  MemeViewController.m
//  reacticons
//
//  Created by Nong Nghia on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MemeViewController.h"
#import "AppDelegate.h"
#import "Utilities.h"
#import "MemeCreatorViewController.h"
#import "Utilities.h"
#import "ImageDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#define MAX_HIGHT 372.0
#define MAX_WIDTH 320.0


#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)


#define CAMERA_BTN_TAG 1
#define ADDPHOTO_BTN_TAG 2
#define SELECT_BTN 11
#define CANCEL_BTN 12
#define SHARE_BTN 13
#define COPY_BTN 14
#define DELETE_BTN 15

@interface MemeViewController ()

@end

@implementation MemeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    memeListItems=[[NSMutableArray alloc] init];
    memeListItems = [[[(AppDelegate*)[[UIApplication sharedApplication]delegate] dataManager] getMemeList] retain];
    NSLog(@"%d",memeListItems.count);
    if (memeListItems) {
        if (memeListItems.count!=0) {
            [placeHolderLb setHidden:YES];
        }
    }
    
    if (myGridView) {
        [myGridView removeFromSuperview];
        [myGridView release];
        myGridView = nil;
    }
    
    myGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, 368)];
    
    [myGridView setDelegate:self];
    [myGridView setDataSource:self];
    
    //    self.navigationItem.title=[NSString stringWithFormat:@"Favorites (%d)",imageListArray.count];
    
    [self.view insertSubview:myGridView atIndex:0];
    [myGridView reloadData];
    
    
}


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    self.view.backgroundColor=[UIColor blackColor];
    [super viewDidLoad];
    self.navigationItem.title =@"Meme";
    // Do any additional setup after loading the view from its nib.
     takePicture=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(btnWasClicked:)];
    
    [takePicture setTag:CAMERA_BTN_TAG];
//    [self.navigationItem setLeftBarButtonItem:takePicture];
    
    choosePhotos=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnWasClicked:)];

    [choosePhotos setTag:ADDPHOTO_BTN_TAG];
//    [self.navigationItem setRightBarButtonItem:choosePhotos];
    [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:takePicture,choosePhotos, nil]];
    
    popUpBar = [[PopUpViewController alloc] init];
    [popUpBar.view setFrame:CGRectMake(0, 0, 72, 34)];
    [popUpBar.view setHidden:YES];
    [popUpBar setDelegate:self];
    [self.view addSubview:popUpBar.view];
    
    //popup label
    popupLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
    [popupLabel setText:@"Image Copied!"];
    [popupLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [popupLabel setTextColor:[UIColor whiteColor]];
    [popupLabel setTextAlignment:UITextAlignmentCenter];
    [popupLabel setBackgroundColor:[UIColor blackColor]];
    popupLabel.layer.borderColor=[UIColor whiteColor].CGColor;
    popupLabel.layer.borderWidth=2;
    popupLabel.layer.cornerRadius=10;
    [popupLabel setHidden:YES];
    [self.view addSubview:popupLabel];
    [popupLabel setCenter:CGPointMake(self.view.center.x, self.view.center.y+100)];
    
    
    //
    [editBar setHidden:YES];
    [cancelNavBar setHidden:YES];
    
    UIBarButtonItem * editFavorites = [[UIBarButtonItem alloc] initWithTitle:@"Select"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(btnWasClicked:)];
    editFavorites.tag=SELECT_BTN;
    [self.navigationItem setRightBarButtonItem:editFavorites];
    isMultipleSelection = NO;
    [editFavorites release];


}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(IBAction)btnWasClicked:(id)sender{
    NSLog(@"btnwasclicked - %d",[sender tag]);
    [popUpBar.view setHidden:YES];

    
    if ([sender tag]==CAMERA_BTN_TAG) {
        [self showImgPickerWithSourceType:UIImagePickerControllerSourceTypeCamera];

    }
    
    if ([sender tag]==ADDPHOTO_BTN_TAG) {
        [self showImgPickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    
    if ([sender tag]==SELECT_BTN) {
//        [popUpBar.view setHidden:YES];
        
        [copyBtn setTitle:@"Copy"];
        textlb.title=[NSString stringWithFormat:@"0 Photos Selected"];
        
        if (!listSelected) {
            listSelected=[[NSMutableArray alloc] init];
        }
        [Utilities hideTabBar:self.tabBarController];
        [myGridView setFrame:CGRectMake(0, 44, 320, 372)];
        for (NSNumber *index in listSelected) {
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        [listSelected removeAllObjects];
        
        isMultipleSelection = YES;
        [myGridView setEnableMultipleSelection:YES];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        [editBar setHidden:NO];
        [cancelNavBar setHidden:NO];
    }
    if ([sender tag]==CANCEL_BTN) {
        [Utilities showTabBar:self.tabBarController];
        
        [myGridView setFrame:CGRectMake(0, 0, 320, 368)];
        
        for (NSNumber *index in listSelected) {
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        
        [listSelected removeAllObjects];
        isMultipleSelection = NO;
        [myGridView setEnableMultipleSelection:NO];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editBar setHidden:YES];
        [cancelNavBar setHidden:YES];
        [myGridView reloadData];
    }
    
    if ([sender tag]==SHARE_BTN) {
        
        UIActionSheet * actionSheet=[[UIActionSheet alloc] initWithTitle:nil
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                  destructiveButtonTitle:nil
                                       otherButtonTitles:
                     @"Export To Phone Gallery",
                     @"Email",
                     nil];
        [actionSheet setTag:SHARE_BTN];
        [actionSheet showInView:editBar];
        [actionSheet release];
    }
    
    if ([sender tag]==COPY_BTN) {
        NSLog(@"Copy and Messaging");
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSMutableArray *listImage=[[NSMutableArray alloc] init];
        for (NSNumber *index in listSelected) {
            [listImage addObject:[self imageAtIndex:[index intValue]]];
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        [listSelected removeAllObjects];
        pasteboard.images=[listImage retain];
        
        [Utilities showTabBar:self.tabBarController];
        
        [myGridView setFrame:CGRectMake(0, 0, 320, 368)];
        isMultipleSelection = NO;
        [myGridView setEnableMultipleSelection:NO];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editBar setHidden:YES];
        [cancelNavBar setHidden:YES];
        [myGridView reloadData];

    }
    if ([sender tag]==DELETE_BTN) {
      UIActionSheet *  actionSheet=[[UIActionSheet alloc] initWithTitle:nil
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                  destructiveButtonTitle:@"Delete"
                                       otherButtonTitles:nil];
        [actionSheet setTag:DELETE_BTN];
        [actionSheet showInView:editBar];
        [actionSheet release];
    }
   
    

    
    
}


-(void)showImgPickerWithSourceType:(UIImagePickerControllerSourceType)sourceType{
    if ([UIImagePickerController isSourceTypeAvailable:sourceType] == NO){
        return;
    }
    
    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    cameraUI.sourceType = sourceType;
    
    cameraUI.mediaTypes =
    [UIImagePickerController availableMediaTypesForSourceType:
     sourceType];
    
    cameraUI.allowsEditing = YES;
    
    cameraUI.delegate = self;
    
    
    [self presentModalViewController: cameraUI animated: YES];
}
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES
                                 completion:^{
                                     NSLog(@"done");
                                 }];
    }
    else {
        [self dismissModalViewControllerAnimated: YES];
        
    }    [picker release];
}

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showLoadingView];
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    
    //    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
    NSLog(@"mediatype:%@",mediaType);
    if ([mediaType isEqualToString:@"public.image"]) {
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }  
    }


    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES 
                                 completion:^{
                                     NSLog(@"done");
                                     [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
                                     [self showMemeCreator:imageToSave];

                                     
                                 }];
    }
    else {
//        [picker dismissModalViewControllerAnimated:YES];

        [picker dismissModalViewControllerAnimated:NO];

        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
        [self showMemeCreator:imageToSave];


        
        
    }
    [picker release];
    
    
    
}
-(void)showMemeCreator:(UIImage*)img{
    MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
    [mcvc setImage:img];   
    [self presentModalViewController:mcvc animated:YES];
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    NSLog(@"%@",viewController);
}



#pragma mark - utilities

#pragma mark - Grid View Data Source

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    return [memeListItems count];
}

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{
    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    if ([memeListItems count] == 0) {
        return nil;
    }
    Items * item = [memeListItems objectAtIndex:cellIndex];
    [cell setImageURLString:item.image];
    
    if (listSelected) {
        for (NSNumber *index in listSelected) {
            if ([index intValue]==cellIndex) {
                [cell setAccessoryType:UIGridViewCellAccessorySelected];
                [cell setIsSelected:YES];
                break;
            }
            else
            {
                [cell setAccessoryType:UIGridViewCellAccessoryNone];
                [cell setIsSelected:NO];
            }
        }
    }
    
    [cell setAccessoryType:UIGridViewCellAccessoryNone];

    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.textLabel setHidden:YES];
    
    
    
    return cell;
}

#pragma mark - Grid View Delegate

- (void)gridView:(UIGridView *)gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
    if (!isMultipleSelection) {
        
        CGPoint offsetPoint = gridView.contentOffset;
        
        CGRect frame = [[myGridView cellAtIndex:cellIndex] frame];
        
        [popUpBar setSelectedFrame:CGRectMake(frame.origin.x - offsetPoint.x,
                                              frame.origin.y - offsetPoint.y,
                                              frame.size.width,
                                              frame.size.height)];
        
        
        if ([Utilities checkFavoriteAdded:[[(Items*)[memeListItems objectAtIndex:cellIndex] image] lastPathComponent]]) {
            [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_btn.png"]
                                          forState:UIControlStateNormal];
            
        }
        else {
            [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_empty_btn.png"]
                                          forState:UIControlStateNormal];
            
        }    if (selectedCellIndex == cellIndex)
        {
            [popUpBar.view setHidden:!popUpBar.view.hidden];
        }
        else {
            [popUpBar.view setHidden:NO];
        }
        selectedCellIndex = cellIndex;
        [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];
        [self.view bringSubviewToFront:popupLabel];
        [UIView beginAnimations:@"showPopupLabel" context:NULL];
        [UIView setAnimationDelay:1];
        [popupLabel setHidden:NO];
        [UIView commitAnimations];
        
        //    [popupLabel performSelector:@selector(setHidden:) withObject:[NSNumber numberWithInt:1] afterDelay:2];
        [self performSelector:@selector(hidePopupLabel) withObject:nil afterDelay:1];
   
    }
    else {
        BOOL isAdd=NO;
        for (int i=0;i<listSelected.count;i++) {
            if ([[listSelected objectAtIndex:i] intValue]==cellIndex) {
                [[myGridView cellAtIndex:cellIndex] setIsSelected:NO];
                [listSelected removeObjectAtIndex:i];
                isAdd=YES;
                break;
            }
        }
        if (!isAdd) {
            [listSelected addObject:[NSNumber numberWithInt:cellIndex]];
        }
        
        if ([listSelected count]>5) {
            [copyBtn setTitle:@"Copy"];
            [copyBtn setEnabled:NO];
        }
        else {
            [copyBtn setEnabled:YES];
            if (listSelected.count>0) {
                [copyBtn setTitle:[NSString stringWithFormat:@"Copy (%d)",listSelected.count]];
            }
            else {
                [copyBtn setTitle:@"Copy"];
            }
        }
        textlb.title=[NSString stringWithFormat:@"%d Photos Selected",listSelected.count];
        
    }
<<<<<<< .mine
        
=======
    else {
        [popUpBar.view setHidden:NO];
    }
    selectedCellIndex = cellIndex;
    [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];
    [self.view bringSubviewToFront:popupLabel];
    [UIView beginAnimations:@"showPopupLabel" context:NULL];
    [UIView setAnimationDelay:1];
    [popupLabel setHidden:NO];
    [UIView commitAnimations];
    
>>>>>>> .r78
    //    [popupLabel performSelector:@selector(setHidden:) withObject:[NSNumber numberWithInt:1] afterDelay:2];
    [self performSelector:@selector(hidePopupLabel) withObject:nil afterDelay:1];
    
}

#pragma mark - POPUP Delegate

- (void)popUpBar:(PopUpViewController *)popUpController didSelectButton:(id)sender
{
    [self popupDidSelectBtnTag:[sender tag]];
    [popUpBar.view setHidden:YES];
}

-(void)popupDidSelectBtnTag:(int)tag{
    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
    
    NSLog(@"popupDidSelectBtnTag:%d",tag);

    ImageDetailViewController * detailView;
    switch (tag) {
        case 0:
            NSLog(@"Share");
            [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            break;
            
        case 1:
            
            if ([Utilities checkFavoriteAdded:[[(Items*)[memeListItems objectAtIndex:selectedCellIndex] image] lastPathComponent]]) {
//                [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_empty_btn.png"] forState:UIControlStateNormal];
                
                NSLog(@"Remove from Favorites:%d",selectedCellIndex);
                NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *favoritePath=[documentPath stringByAppendingPathComponent:@"Favorites"];
                NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];     
                NSArray *favoriteList=[fm contentsOfDirectoryAtPath:favoritePath error:nil];
                
                
                //find item
                for (NSString *item in favoriteList) {
                    if ([[[[[(Items*)[memeListItems objectAtIndex:selectedCellIndex] image] lastPathComponent] componentsSeparatedByString:@"_"] objectAtIndex:1] 
                         isEqualToString:
                         [[[[item componentsSeparatedByString:@"_"] objectAtIndex:1] componentsSeparatedByString:@"."] objectAtIndex:0]]) {
                        //remove item
                        [fm removeItemAtPath:[favoritePath stringByAppendingPathComponent:item] error:nil];
                        return;
                    }
                }
            }
            else {
//                [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_btn.png"] forState:UIControlStateNormal];
                NSLog(@"Add to Favorites....:%d",selectedCellIndex);
                Items *item=[memeListItems objectAtIndex:selectedCellIndex];
                [Utilities saveImage:[self imageAtIndex:selectedCellIndex] toDocumentSubFolder:@"Favorites" withName:[NSString stringWithFormat:@"%@_%@.png",[Utilities uniqueStringWithPrefix:@"F"],[[[[item image] lastPathComponent] componentsSeparatedByString:@"_"] objectAtIndex:1]]];
            }
            
            
            break;
            
        case 2:
            NSLog(@"View detail");
            detailView = [[ImageDetailViewController alloc] init];
            [detailView setItemList:memeListItems];
            [detailView setItemIndex:selectedCellIndex];
            [detailView setItemType:@"meme"];
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];
            break;
            
        default:
            break;
    }
    if (tag==3) {
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageAtIndex:selectedCellIndex]];
        [self presentModalViewController:mcvc animated:YES];
    }
}
- (UIImage *)imageAtIndex:(NSUInteger)index {
    
    NSLog(@"ImageListViewController - imageAtIndex:%d",index);
    Items *item = [memeListItems objectAtIndex:index];
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *targetPath=[documentPath stringByAppendingPathComponent:@"Meme"];
    NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
    
    if ([fm fileExistsAtPath:targetPath]) {
        return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[[item image] lastPathComponent]]];
    }
    else {
        return nil;
    }
}

<<<<<<< .mine
-(void)hidePopupLabel{
    [UIView beginAnimations:@"hidePopupLabel" context:NULL];
    [UIView setAnimationDelay:1];
    [popupLabel setHidden:YES];
    [UIView commitAnimations];
}

#pragma mark - UIActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([actionSheet tag]==SHARE_BTN) {
        if (buttonIndex==0) {
            
            
            [Utilities showTabBar:self.tabBarController];
            for (NSNumber *index in listSelected) {
                UIImageWriteToSavedPhotosAlbum([self imageAtIndex:[index intValue]], nil,nil,nil);
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            
            [myGridView setFrame:CGRectMake(0, 0, 320, 368)];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            
            memeListItems = [[[(AppDelegate*)[[UIApplication sharedApplication]delegate] dataManager] getMemeList] retain];
            self.navigationItem.title=[NSString stringWithFormat:@"Custom (%d)",memeListItems.count];
            [myGridView reloadData];
            return;
        }
        if (buttonIndex==1) {
            
            [self sendMail];
            
            
            return;
        }
    }
    
    if ([actionSheet tag]==DELETE_BTN) {
        if (buttonIndex==0) {
            
            NSLog(@"list:%@",listSelected);
            [Utilities showTabBar:self.tabBarController];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *favoritePath=[documentPath stringByAppendingPathComponent:@"Meme"];
            
            NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
            
            for (NSNumber *index in listSelected) {
                NSLog(@"delete:%@",[NSURL URLWithString:[(Items*)[memeListItems objectAtIndex:[index intValue]] image]]);
                [fm removeItemAtURL:[NSURL URLWithString:[(Items*)[memeListItems objectAtIndex:[index intValue]] image]] error:nil];
                [fm removeItemAtPath:[favoritePath stringByAppendingPathComponent:[[(Items*)[memeListItems objectAtIndex:[index intValue]] image] lastPathComponent]] error:nil];
            }
            [listSelected removeAllObjects];
            memeListItems = [[[(AppDelegate*)[[UIApplication sharedApplication]delegate] dataManager] getMemeList] retain];
            self.navigationItem.title=[NSString stringWithFormat:@"Custom (%d)",memeListItems.count];
            [myGridView setFrame:CGRectMake(0, 0, 320, 368)];
            
            [myGridView reloadData];
            [myGridView scrollsToTop];
            
            return;
        }
        
    }
}

#pragma mark - MFMailComposeViewController Delegate

-(void)sendMail{
    
    if ([MFMailComposeViewController canSendMail]) {
        
        // Fill out the email body text
        //Create a string with HTML formatting for the email body
        NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:@"<html><body>"] retain];
        //Add some text to it however you want
        [emailBody appendString:@"<p>Some email body text can go here</p>"];
        [emailBody appendString:@"</body></html>"];
        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;
        [emailDialog setSubject:@"My Inline Image Document"];
        [emailDialog setMessageBody:emailBody isHTML:YES];
        
        //Pick an image to insert
        //This example would come from the main bundle, but your source can be elsewhere
        for (NSNumber *index in listSelected) {
            
            UIImage *emailImage = [self imageAtIndex:[index intValue]];
            
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
            
            [emailDialog addAttachmentData:imageData mimeType:@"png" fileName:[[(Items*)[memeListItems objectAtIndex:[index intValue]] image] lastPathComponent]];
            
        }
        
        
        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
        [emailBody release];
        
        
    }
    else {
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Cannot Send Via Mail" message:@"Please setup your mail before share via Email" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    [Utilities showTabBar:self.tabBarController];
    for (NSNumber *index in listSelected) {
        [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
    }
    [myGridView setFrame:CGRectMake(0, 0, 320, 368)];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [editBar setHidden:YES];
    [cancelNavBar setHidden:YES];
    
    memeListItems = [[[(AppDelegate*)[[UIApplication sharedApplication]delegate] dataManager] getMemeList] retain];
    self.navigationItem.title=[NSString stringWithFormat:@"Custom (%d)",memeListItems.count];
    
    isMultipleSelection = NO;
    [myGridView setEnableMultipleSelection:NO];
    [myGridView reloadData];
    
}

-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
    [self dismissModalViewControllerAnimated:YES];
    
}



=======
-(void)hidePopupLabel{
    [UIView beginAnimations:@"hidePopupLabel" context:NULL];
    [UIView setAnimationDelay:1];
    [popupLabel setHidden:YES];
    [UIView commitAnimations];
}

>>>>>>> .r78
@end
